//
//  HMEmoticonToolbar.swift
//  Weibo
//
//  Created by Apple on 2017/7/17.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
//  表情类型
enum EmoticonType: Int {
    //  最近
    case recent = 1000
    //  默认
    case normal = 1001
    //  emoji
    case emoji = 1002
    //  浪小花
    case lxh = 1003
}

//  表情键盘toolbar
class HMEmoticonToolbar: UIStackView {

    //  记录上次选中的按钮
    var lastSelectedButton: UIButton?
    //  点击toolbar表情按钮的闭包
    var callBack: ((EmoticonType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件
    private func setupUI() {
        self.axis = .horizontal
        self.distribution = .fillEqually
        
        addChildButton(title: "最近", imgName: "compose_emotion_table_left", type: .recent)
        addChildButton(title: "默认", imgName: "compose_emotion_table_mid", type: .normal)
        addChildButton(title: "Emoji", imgName: "compose_emotion_table_mid", type: .emoji)
        addChildButton(title: "浪小花", imgName: "compose_emotion_table_right", type: .lxh)
    }
    
    //  添加子按钮
    private func addChildButton(title: String, imgName: String, type: EmoticonType) {
        let button = UIButton()
        button.tag = type.rawValue
        button.addTarget(self, action: #selector(btnAction(btn: )), for: .touchUpInside)
        button.setTitle(title, for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .selected)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.setBackgroundImage(UIImage(named: imgName + "_normal"), for: .normal)
        button.setBackgroundImage(UIImage(named: imgName + "_selected"), for: .selected)
        button.adjustsImageWhenHighlighted = false
        addArrangedSubview(button)
        if type == .normal {
            button.isSelected = true
            lastSelectedButton = button
        }
    }

    //  MARK:   --表情按钮点击事件
    @objc private func btnAction(btn: UIButton) {
        if lastSelectedButton == btn {
            return
        }
        lastSelectedButton?.isSelected = false
        btn.isSelected = true
        lastSelectedButton = btn
        //  获取枚举类型
        let type = EmoticonType(rawValue: btn.tag)!
        callBack?(type)
    }
    
    //  根据组数索引选中对应的表情按钮
    func selectEmotionButton(section: Int) {
        //  tag不要设置0，否则获取的不是子视图，而是当前视图自己
        let button = viewWithTag(section + 1000) as! UIButton
        if lastSelectedButton == button {
            return
        }
        lastSelectedButton?.isSelected = false
        button.isSelected = true
        lastSelectedButton = button
    }
    
}
